package com.ztom.daily.n2022.m3;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 两个列表的最小索引总和
 * <p>
 * https://leetcode-cn.com/problems/minimum-index-sum-of-two-lists/
 *
 * @author ZhangTao
 */
public class Day14FindRestaurant {

    public String[] findRestaurant(String[] list1, String[] list2) {
        if (list1 == null || list1.length == 0 || list2 == null || list2.length == 0) {
            return null;
        }

        // 值 - 下标
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < list1.length; i++) {
            map.put(list1[i], i);
        }

        List<String> res = new ArrayList<>();
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < list2.length; i++) {
            if (map.containsKey(list2[i])) {
                Integer j = map.get(list2[i]);
                if (i + j < min) {
                    min = i + j;
                    // 先清空
                    res.clear();
                    res.add(list2[i]);
                } else if (i + j == min) {
                    res.add(list2[i]);
                }
            }
        }
        return res.toArray(new String[0]);
    }
}
